<!-- 课程管理 -->
<template>
    <div class="app-container">
        <!--******************************检索条件*******************************-->
        <el-form :inline="true" :model="pageCourseVo" class="demo-form-inline">
            <el-form-item label="课程标题">
                <el-input v-model="pageCourseVo.title" placeholder="课程标题"></el-input>
            </el-form-item>
            <el-form-item label="讲师" v-if="!isTeacher()||!classId">
                <el-input v-model="pageCourseVo.teacherName" placeholder="讲师名"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="pageCourseVo.status" clearable placeholder="请选择">
                    <el-option :key="1" label="已发布" value="Normal"></el-option>
                    <el-option :key="2" label="未发布" value="Draft"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="分类">
                <el-cascader
                    placeholder="请选择"
                    :options="subjects"
                    filterable
                    clearable
                    @change="handleSubjectChange"
                    :props="subjectProps"
                ></el-cascader>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                    v-model="beginEndTime"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="right"
                    value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getCourses()">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click=" mangeCourseRoute()">添加</el-button>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="danger"
                    :disabled="deleteBatchButton"
                    @click="removeCourseByIds(multipleSelection)"
                >批量删除</el-button>
            </el-form-item>
        </el-form>

        <!--******************************数据*******************************-->
        <el-table
            :data="courses"
            style="width: 100%"
            v-loading="loading"
            stripe
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand">
                        <el-form-item label="标题">
                            <span>{{ props.row.title }}</span>
                        </el-form-item>
                        <el-form-item label="讲师">
                            <span>
                                <el-avatar size="large" :src="props.row.teacherAvatar"></el-avatar>
                            </span>
                        </el-form-item>
                        <el-form-item label>
                            <span>{{props.row.teacherName}}</span>
                        </el-form-item>

                        <el-form-item label="所属分类">
                            <span>{{ getSubjectName(props.row.subjectId,props.row.subjectParentId) }}</span>
                        </el-form-item>
                        <el-form-item label="状态">
                            <span>
                                <el-tag type="success" v-if="props.row.status==='Normal'">已发布</el-tag>
                                <el-tag type="warning" v-else>未发布</el-tag>
                            </span>
                        </el-form-item>
                        <el-form-item label="创建时间">
                            <span>{{ props.row.gmtCreate }}</span>
                        </el-form-item>
                        <br />
                        <el-form-item label="价格">
                            <span>{{ props.row.price+"元" }}</span>
                        </el-form-item>
                        <el-form-item label="课时">
                            <span>{{ props.row.lessonNum }}</span>
                        </el-form-item>
                        <el-form-item label="购买量">
                            <span>{{ props.row.buyCount }}</span>
                        </el-form-item>
                        <el-form-item label="观看量">
                            <span>{{ props.row.viewCount}}</span>
                        </el-form-item>
                        <br />
                        <el-form-item label="封面">
                            <span>
                                <el-image
                                    style="width: 200px; height: 200px"
                                    :src="props.row.cover"
                                    fit="contain"
                                ></el-image>
                            </span>
                        </el-form-item>
                        <el-form-item label="描述">
                            <span v-html="props.row.description"></span>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="课程标题" prop="title"></el-table-column>
            <el-table-column label="封面">
                <template slot-scope="scope">
                    <el-image
                        style="width: 150px; height: 100px"
                        :src="scope.row.cover"
                        fit="contain"
                    ></el-image>
                </template>
            </el-table-column>
            <el-table-column label="讲师">
                <template slot-scope="scope">
                    {{scope.row.teacherName}}
                    <br />
                    <el-tooltip placement="top">
                        <div slot="content">
                            <el-image
                                style="width: 150px; height: 150px"
                                :src="scope.row.teacherAvatar"
                                fit="contain"
                            ></el-image>
                        </div>
                        <el-avatar :size="45" fit="contain" :src="scope.row.teacherAvatar"></el-avatar>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.status==='Normal'">已发布</el-tag>
                    <el-tag type="warning" v-else>未发布</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>

            <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                    <el-button
                        type="primary"
                        size="small"
                        @click="mangeCourseRoute(scope.row.id)"
                    >修改</el-button>
                    <el-button
                        type="danger"
                        v-if="scope.row.status==='Draft'"
                        @click="removeCourseById(scope.row.id)"
                        size="small"
                    >删除</el-button>
                    <el-button
                        type="warning"
                        v-if="scope.row.status==='Draft'"
                        size="small"
                        @click="updateCourse(scope.row)"
                    >发布</el-button>
                    <el-button type="info" v-else size="small" @click="updateCourse(scope.row)">下线</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--******************************分页*******************************-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :current-page="current"
            :page-sizes="[6, 15, 20, 30, 40, 50]"
            :page-size="limit"
            :hide-on-single-page="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>

        <el-backtop :visibility-height="100"></el-backtop>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {
    pageCourse,
    deleteCourseByIds,
    updateCourse,
} from "@/api/course/course";
import { getById } from "@/api/ucenter/teacher";
import { getSubject } from "@/api/course/subject";
export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    props: ["classId"],
    data() {
        //这里存放数据
        return {
            //检索表单
            subjectProps: { checkStrictly: true, value: "id" },
            beginEndTime: "",
            subjects: [],
            pageCourseVo: {
                teacherName: "",
                subjectId: "",
                subjectParentId: "",
                title: "",
                status: "",
                beginTime: "",
                endTime: "",
            },
            //分液器
            current: 1,
            limit: 6,
            total: 0,

            //表格数据
            courses: [],
            loading: true, //表格转圈圈
            multipleSelection: [],
        };
    },
    //监听属性 类似于data概念
    computed: {
        deleteBatchButton() {
            return this.multipleSelection.length === 0;
        },
    },
    //监控data中的数据变化
    watch: {
        beginEndTime(newValue, oldValue) {
            if (newValue) {
                this.pageCourseVo.beginTime = newValue[0];
                this.pageCourseVo.endTime = newValue[1];
            } else {
                this.pageCourseVo.beginTime = "";
                this.pageCourseVo.endTime = "";
            }
        },
    },
    //方法集合
    methods: {
        getCourses(page = 1) {
            this.current = page;
            this.loading = true;
            if (this.classId) {
                this.pageCourseVo.classId = this.classId;
            }
            pageCourse(this.pageCourseVo, this.current, this.limit).then(
                (response) => {
                    this.courses = response.data.courses;
                    this.total = response.data.rows;
                    for (let i = 0; i < this.courses.length; i++) {
                        let teacherId = this.courses[i].teacherId;
                        getById(teacherId).then((response) => {
                            this.courses[i].teacherAvatar =
                                response.data.teacher.avatar;
                        });
                    }
                    this.loading = false;
                }
            );
        },
        handleSizeChange(val) {
            this.current = parseInt((this.current * this.limit) / val);
            this.limit = val;
            this.getCourses(this.current);
        },
        handleCurrentChange(val) {
            this.getCourses(val);
        },
        handleSelectionChange(val) {
            this.multipleSelection = [];
            for (var i = 0; i < val.length; i++) {
                this.multipleSelection.push(val[i].id);
            }
        },
        getAllSubject() {
            getSubject().then((response) => {
                this.subjects = response.data.cateGoryTree;
            });
        },
        handleSubjectChange(val) {
            this.pageCourseVo.subjectParentId = val[0];
            this.pageCourseVo.subjectId = val[1];
        },
        removeCourseByIds(ids) {
            //过滤一下已经发布的课程
            let idList = ids.filter((item) => {
                for (let i = 0; i < this.courses.length; i++) {
                    if (
                        this.courses[i].id === item &&
                        this.courses[i].status === "Normal"
                    ) {
                        return false;
                    }
                }
                return true;
            });
            if (ids.length !== idList.length) {
                this.$confirm(
                    "包含了已发布的课程,若继续只会删除未发布的",
                    "提示",
                    {
                        confirmButtonText: "继续",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                )
                    .then(() => {
                        this.$confirm("确定要删除吗?", "提示", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning",
                        })
                            .then(() => {
                                deleteCourseByIds(ids).then((response) => {
                                    this.getCourses();
                                    this.$message({
                                        type: "success",
                                        message: "删除成功!",
                                    });
                                });
                            })
                            .catch(() => {});
                    })
                    .catch(() => {});
            } else {
                this.$confirm("确定要删除吗?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        deleteCourseByIds(ids).then((response) => {
                            this.getCourses();
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                        });
                    })
                    .catch(() => {});
            }
        },
        removeCourseById(id) {
            this.$confirm("确定要删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteCourseByIds([id]).then((response) => {
                        this.getCourses();
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                    });
                })
                .catch(() => {});
        },
        updateCourse(course) {
            this.$confirm("确定要做此操作吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    course.status =
                        course.status === "Draft" ? "Normal" : "Draft";
                    updateCourse(course).then((response) => {
                        this.$message({
                            message: "成功",
                            type: "success",
                        });
                    });
                })
                .catch(() => {});
        },
        getSubjectName(subjectId, subjectParentId) {
            let s1 = "",
                s2 = "",
                subjectParentIndex;
            for (let i = 0; i < this.subjects.length; i++) {
                if (
                    this.subjects[i].id === subjectParentId &&
                    subjectParentId !== 0
                ) {
                    s2 = this.subjects[i].label;
                    subjectParentIndex = i;
                    break;
                }
            }
            for (
                let i = 0;
                i < this.subjects[subjectParentIndex].children.length;
                i++
            ) {
                if (
                    this.subjects[subjectParentIndex].children[i].id ===
                    subjectId
                ) {
                    s1 = this.subjects[subjectParentIndex].children[i].label;
                }
            }
            if (s1 !== "") {
                return s2 + "/" + s1;
            } else {
                return s2;
            }
        },
        mangeCourseRoute(id) {
            if (!this.classId) {
                this.$router.push({
                    name: "CourseAdd",
                    params: { id: id },
                });
            } else {
                let tmp = this.classId;
                this.$router.push({
                    name: "ClassCourseMange",
                    params: { id: id, classId: tmp },
                });
            }
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.getCourses();
        this.getAllSubject();
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
};
</script>
<style scoped>
</style>